<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <full-screen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :check-box="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :isDynamic="true"
                >
                  <template v-slot:col-price="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}[price]`"
                      :rules="
                        scope.$index >= 0
                          ? {
                              validator: $validate.positiveMoney,
                              trigger: 'blur',
                            }
                          : {}
                      "
                    >
                      <el-input-number
                        v-model="scope.row.price"
                        controls-position="right"
                        style="width: 100%; margintop: 18px"
                        :precision="systemConfig.price_precision"
                        :step="1"
                        :min="0"
                        :max="999999999999999"
                        @change="
                          changePrice($event, `data.${scope.$index}.price`)
                        "
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
  </div>
</template>
<script setup name="estimationConfirmationOrderModify">
import FullScreen from '@/components/FullScreen/index'
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import { getCustomizeSetting } from '@/api/customize'
import {
  getEstimationConfirmationOrderDetailCustomizeListAll,
  getEstimationConfirmationById,
  createEstimationConfirmation,
  putEstimationConfirmation,
  selectFromReceivingOrder,
  selectFromReceivingOrderDetail,
} from '@/api/stock.js'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'title', 'orderId', 'receiveId'])

const systemConfig = proxy.$store.state.permission.systemConfig
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '来源单号',
      value: 'sourceOrderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库仓库',
      value: 'depotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库时间',
      value: 'storeTime',
      type: 'input',
      disabled: true,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.orderId,
      },
    },
    queryParams: {
      receivingOrderId: props.receiveId,
    },
  },
})
const tableInfo = reactive({
  data: [],
  fieldList: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
})

const formRefs = ref('')

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let calcQty = row.calcQty || 0
      let unitConvertCoefficient = row.unitConvertCoefficient || 1
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, parseFloat(row.price || 0)),
        unitConvertCoefficient
      )
    })
  },
  {
    deep: true,
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})

let obj = {
  price: {
    label: '单价',
    value: 'price',
    width: '250px',
    type: 'slot',
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('estimationConfirmationOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function save() {
  proxy.$fn
    .checkForm(formRefs.value)
    .then(() => {
      let api = props.orderId
        ? putEstimationConfirmation
        : createEstimationConfirmation
      let param = {
        ...formInfo.data,
        mergeDetails: tableInfo.data,
      }
      api(param).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emit('returnModify', false)
        }
      })
    })
    .catch(() => {
      proxy.$message({
        message: '必填或非法校验未通过，请检查！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    })
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function getMain() {
  getEstimationConfirmationById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      setBusinessDate()
    }
  })
}
function getList() {
  getEstimationConfirmationOrderDetailCustomizeListAll(filterInfo.query).then(
    (res) => {
      if (res && res.success) {
        tableInfo.data = res.data
      }
    }
  )
}
function getReceiveMain() {
  selectFromReceivingOrder(props.receiveId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      setBusinessDate()
    }
  })
}
function getReceviceList() {
  selectFromReceivingOrderDetail(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'EstimationConfirmationOrderDetailModify-com.slip.spd.entity.vo.stock.EstimationConfirmationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      if (props.receiveId) {
        getReceiveMain()
        getReceviceList()
      } else if (props.orderId) {
        getMain()
        getList()
      }
    }
  })
}
</script>
